<?php if (!defined("_ECRIRE_INC_VERSION")) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

include_spip('functions/pdk_common');
include_spip('classes/AlohacartException');

function formulaires_alohacart_order_product_traiter_dist($id_order){
    $order_product_mdl = pdk_load_class('AlohacartOrderProductModel','classes');
    $product_mdl = pdk_load_class('ProductModel','classes');
	$result = array();
    
    try {
        // Add product
        include_spip('spip_bonux_fonctions');
        $selected_article = picker_selected(_request('id_article_add'), 'article');       
        $id_article_add = intval($selected_article[0]);
        $quantity = intval(_request('quantity'));                
        if ($id_article_add && $quantity > 0) {
            $product = $product_mdl->select_by_id($id_article_add);
            $order_product = array();
            $order_product['id_order'] = $id_order;
            $order_product['id_article'] = $id_article_add;
            $order_product['sku'] = $product['sku'];
            $order_product['titre'] = $product['titre'];
            $order_product['quantity'] = $quantity;
            $order_product['price'] = $product['price'];
            $order_product['total_price'] = $product['price']*$quantity;            
            if (!$order_product_mdl->insert($order_product))
                throw new AlohacartException("Order product insert fail!");
        }
        
        
        $id_order_product_delete = intval(_request('id_order_product_delete'));        
        if ($id_order_product_delete) {
            if (!$order_product_mdl->delete_by_id($id_order_product_delete))
                throw new AlohacartException("Order product delete fail!");
        }
        
                        
        /*$data = $order_mdl->form_data_from_array($_REQUEST);                        
        if (!$order_mdl->update_by_id($id_order, $data, true))
            throw new Exception("Product save fail!");*/
        
        $result['message_ok'] = _T('alohacart:form_saved');    
    } catch(Exception $e) {
        $result['message_erreur'] = _T('alohacart:form_error');        
        //$result['message_erreur'] = $e->getMessage();
    }        
    
    set_request('id_article_add');
    set_request('id_order_product_delete');
    
    return $result;
}
